/*
 * Created by Federico Pisarello - SisDev Software (c) 2012 - fpisarello@sisdevsoft.com
 */

var popForm = 'ptosueltaPop.php';
var actionForm = 'ptosueltaAction.php';

var joDataPtoSuelta;
var oTable;

/** Variable of tracking the IndexPK **/
var actionPK = undefined;
var action = undefined;

function $_init()
{
	$('#btnPtosuelta').removeClass('btnMenu').addClass('btnMenuAct');
	
	var gaiSelected;
	
	$(document).ready(function() {
    	oTable = $('#dt_ptoSuelta').dataTable( {
					"bJQueryUI": true,
					"sPaginationType": "two_button",
					"bInfo": false,
					"bLengthChange": false,
					"bProcessing": true,
					"bServerSide": true,
					"sAjaxSource": actionForm + "?actionOfForm=search",
					"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
						if ( jQuery.inArray(aData[0], gaiSelected) != -1 )
						{
					        $(nRow).addClass('row_selected');
						}
						return nRow;
					},
					"aoColumns": [
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null
					  		]

				});
    	
    	/* Click event handler */
    	$('#dt_ptoSuelta tbody tr').live('click', function () {
    		var aData = oTable.fnGetData(this);
    		var iId = aData[0];
    		actionPK = aData[0];
    		
    		gaiSelected =  [];
    		if ( $(this).hasClass('row_selected') ) {
	            $(this).removeClass('row_selected');
	            actionPK = undefined;
	        }
	        else {
	            oTable.$('tr.row_selected').removeClass('row_selected');
	            $(this).addClass('row_selected');
	            gaiSelected[gaiSelected.length++] = iId;
	        }
    	} );

	});
	
	$("#ptoSueltaDialog").dialog({
		autoOpen:false, 
		height:500, 
		width:600, 
		dialogClass:'no-close',
		beforeClose: function() { $_ClearPtoSueltaPopForm(); },
		open: function() {
			$('#ptoSueltaDialog').css('background','url(imagenes/fondo_texto.jpg)');
			$('#btnSave').click( function(e) {
				$('#ptoSueltaPopForm').submit();
			});
		}
	});
	
	//Add Click for All Buttons in Search Form
	$("#btnAdd").click( function(e) {
		addProxyShow();
    });
	
	$('#btnEdit').click( function(e) {
		editProxyShow();
	});
	
	$('#btnErase').click( function(e) {
		delProxyShow();
	});
}

function $_initPop()
{
	$(".numeric").numeric();
	
	//Add Click for All Buttons in Pop Form
	$('#btnExit').click( function(e) {
		$('#ptoSueltaDialog').dialog('close');
	});
	
	$('#description').blur( function(e) {
		$_searchWeatherCity();
	});
	
	$_ValidatorSetDefaults();
	$_initPopValidator();
	
	//Populate Pto Suelta Data	
	if(action == iConst.EDIT)
	{
		$('#description').val(joDataPtoSuelta.description);
		$('#codPos').val(joDataPtoSuelta.codPos);
		$('#province').val(joDataPtoSuelta.province);
		$('#latDeg').val(joDataPtoSuelta.latDeg);
		$('#latMin').val(joDataPtoSuelta.latMin);
		$('#latSeg').val(joDataPtoSuelta.latSeg);
		$('#lngDeg').val(joDataPtoSuelta.lngDeg);
		$('#lngMin').val(joDataPtoSuelta.lngMin);
		$('#lngSeg').val(joDataPtoSuelta.lngSeg);
		$('#kmts').val(joDataPtoSuelta.kmts);
		$('#weatherLocation').val(joDataPtoSuelta.weatherCode);
	}
}

function $_searchWeatherCity()
{
	if($('#description').val() == '')
		return;
	
	if($('#weatherLocation').val() != '')
		return;
	
	// Cache results for an hour to prevent overuse
	now = new Date();

	// Create Yahoo Weather feed API address
	var query = 'select * from geo.places where text="'+ $('#description').val() +'"';
	var api = 'http://query.yahooapis.com/v1/public/yql?q='+ encodeURIComponent(query) +'&rnd='+ now.getFullYear() + now.getMonth() + now.getDay() + now.getHours() +'&format=json&callback=?';

	// Send request
	$.ajax({
		type: 'GET',
		url: api,
		dataType: 'json',
		success: function(data) {

			if (data.query.count > 0 ) {						

				html = '<span>'+ data.query.count +' location';

				if (data.query.count > 1) html = html + 's';
				html = html + ' found:</span><ul>';

				// List multiple returns
				if (data.query.count > 1) {
					for (var i=0; i<data.query.count; i++) {
						html = html + '<li>'+ _getWeatherAddress(data.query.results.place[i]) +'</li>';
					}
				} else {
					html = html + '<li>'+ _getWeatherAddress(data.query.results.place) +'</li>';
				}

				html = html + '</ul>';
				
				$('#weatherList').html(html);

			} else {
				$('#weatherList').html('The location could not be found');
			}
		},
		error: function(data) {
			$('#weatherList').html('Ocurrio un Error');
		}
	});	
}

function _getWeatherAddress(data) {

	// Get address
	var address = data.name;
	if (data.admin2) address += ', ' + data.admin2.content;
	if (data.admin1) address += ', ' + data.admin1.content;
	address += ', ' + data.country.content;

	// Get WEOID
	var woeid = data.woeid;

	return '<a class="weatherAddress" href="javascript:;" onclick="$_pushWoeid(' + woeid +')">'+ address +'</a>';
}

function $_pushWoeid(woeid)
{
	$('#weatherLocation').val(woeid);
}

function addProxyShow()
{
	//Reset State of action and IndexPK
	actionPK = undefined;
	action = iConst.NEW;
	oTable.$('tr.row_selected').removeClass('row_selected');
	$('#ptoSueltaDialog').load(popForm).dialog('open');
}

function editProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
		return;
	}
	
	action = iConst.EDIT;
	var paramData =  "actionOfForm=" + iConst.EDIT + "&idPtoSuelta=" + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj)
                            {
        						joDataPtoSuelta = jsonObj;
        						//Open Pop Dialog
        						$('#ptoSueltaDialog').load(popForm).dialog('open');
                            }
        });
	
return true;
}

function $_savePtoSuelta(action)
{
	var paramData = 'actionOfForm=addOrEdit&' + $("#ptoSueltaPopForm").serialize();
	
	if(action == iConst.EDIT)
		paramData += '&idPtoSuelta=' + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj){
            if(jsonObj.status === 'OK'){
				$_showMessage('OK', jsonObj.status, jsonObj.msg);
				$('#ptoSueltaDialog').dialog('close');
				oTable.fnReloadAjax();
			}
			else
				$_showMessage('ERR', jsonObj.status, jsonObj.msg);
        }
    });

return true;
}

function delProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
		return;
	}
	
	action = iConst.DELETE;
	
	$("#deletePtoSueltaDialog").dialog({
		autoOpen: false, 
		width:350,
		position: 'center',
		open: function () {
			$('#deletePtoSueltaDialog').css('background','url(imagenes/fondo_texto.jpg)');
			$('#btnConfirmDelete').click( function(e) {
				$_del();
			});
			$('#btnExitDelete').click( function(e) {
				$('#deletePtoSueltaDialog').dialog('close');
			})
		}
	});
	$('#deletePtoSueltaDialog').dialog('open');	
}

function $_del()
{
	var paramData = 'actionOfForm=' + action + '&idPtoSuelta=' + actionPK;

    $.ajax({
            type: 'POST',
            url: actionForm,
            data: paramData,
			dataType: 'json',
            success: function(jsonObj)
                                {
                                    if(jsonObj.status === 'OK'){
										$_showMessage('OK', 'OK', jsonObj.msg);
										
										//Reset State of action and IndexPK
										actionPK = undefined;
										action = iConst.NEW;
										oTable.fnReloadAjax();
									}
									else
										$_showMessage('ERR', 'ERROR', jsonObj.msg);
                                    $('#deletePtoSueltaDialog').dialog('close');
                                }
            });

return true;
}

function $_initPopValidator()
{
	$('#ptoSueltaPopForm').validate({
		submitHandler: function() {
			$_savePtoSuelta(action);
		}, 		
		rules: {
			description: {required: true,minlength: 1},
			province: {required: true,minlength: 1},
			latitude: {required: true,minlength: 1},
			longitude: {required: true,minlength: 1},
			kmts: {required: true,minlength: 1},
			weatherLocation: {required: true,minlength: 1}
		},
		messages: {
			description: {required: '',minlength: ''},
			province: {required: '',minlength: ''},
			latitude: {required: '',minlength: ''},
			longitude: {required: '',minlength: ''},
			kmts: {required: '',minlength: ''},
			weatherLocation: {required: '',minlength: ''}
		}
	});
}

function $_ClearPtoSueltaPopForm()
{	
	$("#ptoSueltaDialog").empty();
}